<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>

<body>
  <div id="app">
    <p mv-text="name"></p>
    <p mv-text="name"></p>
    <h3 mv-text="age"></h3>
    <h3 mv-text="age"></h3>
  </div>
  <script>
    let Watcher = function () {

    }
    Watcher.prototype.setDom = function (rootDom, key) {

      let selStr = `[mv-text="${key}"]`
      this[key] = rootDom.querySelectorAll(selStr)
    }
    // 对应dom变量更新
    Watcher.prototype.notify = function (key, nv) {
      // 获取变量对应的dom集合
      let domList = this[key]
      for (let i = 0; i < domList.length; i++) {
        // 完成dom属性更新
        domList[i].textContext = nv

      }
    }
    // 统一初始化数据更新方法
    Watcher.prototype.update = function (data) {
      for (let key in data) {
        this.notify(key, data[key])
      }
    }
    let Mvvm = function (options) {
      this.init(options.el, options.data)

    }
    //depency依赖 完成数据每个变量劫持操作 把数据绑定到this当前vue实例上
    Mvvm.prototype.init = function (el, data) {
      // 提供对应的DOM容器
      this.$el = document.querySelector(el)
      //将数据私有化为临时变量==>为了this._data数据劫持
      this._data = data
      // 将数据变量完成get set数据劫持
      this.deps(data)
    }
    Mvvm.prototype.deps = function (data) {
      //  完成变量和页面元素的依赖
      let watcher = new Watcher()
      console.log(watcher)
      for (let key in data) {
        // 完成当前变量和dom对应关系记录
        watcher.setDom(this.$el, key)
        Object.defineProperty(this, key, {
          get() {
            return data[key]
          },
          set(nv) {
            data[key] = nv
            watcher.notify(key, data[key])

          }
        })
      }
      // 页面数据初始化
      watcher.update(data)


    }

    let vm = new Mvvm({
      el: "#app",
      data: {
        name: 'lisi',
        age: 20,
        gender: 'sex'
      }
    })
    console.log(vm)
  </script>
</body>

</html>